﻿using System.Collections.Generic;
using Macds.Core.IoC;

namespace Macds.Core.Task
{
    public class TaskManager
    {
        private List<TaskProcess> tasks;
        private DependencyFactory ioC;

        public TaskManager()
        {
            this.tasks = new List<TaskProcess>();
            this.ioC = new DependencyFactory();
        }

        #region Public Methods

        public void Start()
        {
            LoadTasks();
        }

        public void Stop()
        {
            StopTasks();
        }

        #endregion

        #region Private Methods

        private void LoadTasks()
        {
            TaskIoC internalTasks = ioC.Create<TaskIoC>("TaskIoC");

            foreach (ITask task in internalTasks.Tasks)
            {
                var process = new TaskProcess(task);
                process.TimerInternal.Start();
                tasks.Add(process);
            }
        }

        private void StopTasks()
        {
            foreach (var process in tasks)
            {
                int counter = 0;
                process.TimerInternal.Stop();
                while (process.Task.InProgress)
                {
                    if (counter > 4)
                        break;
                    System.Threading.Thread.Sleep(500);
                    counter++;
                }
            }
        }

        #endregion
    }
}
